import React, { useEffect, useState } from 'react';
import { withRouter, router } from 'umi';
import { useRequest, useDictionary } from '@/hooks';
import { createForm } from 'rc-form';
import {
    Table,
    Card,
    Button,
    Form,
    Input,
    Row,
    Col,
    Select,
    DatePicker,
    Tooltip,
    Radio,
    Spin,
    Empty,
    message
} from 'antd';
import Pagination from '@/components/Pagination';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Icon from '@/components/IconPro';
import moment from 'moment';
import TodoCard from '@/components/TodoCard';
import { parseLocation } from '@/utils/utils';
import { newTabProps } from '@/utils/tab';
import useSubscribeMsg from '@/hooks/useSubscribeMsg';
import Msg from '@/hooks/useSubscribeMsg/Msg';
import TodoSort from './Components/TodoSort';
import { getTodoList } from './services';

import styles from './index.less';
import { formatDate } from './utils';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { Item } = Form;
const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 }
    }
};
// 待办
const Todo = ({ location, form }) => {
    const { query = {} } = location;
    const {
        pageNo = 1,
        pageSize = 10,
        viewType = 'list',
        pendingState,
        taskTitle,
        taskResource,
        pushRangePicker,
        taskType: tabType = ''
    } = query;
    const { getFieldDecorator, validateFields, setFieldsValue } = form;
    const [expand, setExpand] = useState();
    const [taskType, setTaskType] = useState('');
    const [loading, setLoading] = useState(true);
    const [listData, setListData] = React.useState(undefined);

    // 请求数据
    const { run } = useRequest(
        () =>
            getTodoList({
                pageNo,
                pageSize,
                taskStatus: 0,
                ...query
            }),
        {
            manual: true,
            onSuccess: res => {
                setLoading(false);
                if (res) {
                    const { code, data, msg } = res;
                    if (code === 10000) {
                        setListData(data);
                    } else {
                        // 查找不到user就不弹出提示
                        const isLogin = window.localStorage.getItem('user');
                        if (isLogin) {
                            message.error(msg);
                        }
                    }
                }
            }
        }
    );

    const { unFinishCount, finishCount, pageInfo = {} } = listData || {};
    const { rows: todoList = [], total } = pageInfo || {};

    const [messageResourceList] = useDictionary('messageResource');

    // 操作跳转url
    const handleLink = url => {
        const [pathname, redirectQuery] = parseLocation({ pathname: url });
        history.push({ pathname, query: redirectQuery, ...newTabProps });
    };

    const getOrderState = field => {
        if (!query?.orderByField) {
            return undefined;
        }
        const arr = query.orderByField.split('|');
        if (arr[0] === field) {
            return arr[1];
        }
        return undefined;
    };

    const columns = [
        {
            title: '事项',
            dataIndex: 'taskTitle',
            key: 'taskTitle',
            width: '16%'
        },
        {
            title: '摘要',
            dataIndex: 'abstractList',
            width: '16%',
            render: text => {
                const renderArr = text?.map((item, index) =>
                    index > 3 ? null : (
                        <div className={styles.abstractText}>
                            <span>{item.itemName}：</span>
                            <span>
                                <Tooltip
                                    overlayClassName={styles.todoCardTooltip}
                                    placement="topLeft"
                                    title={item.itemValue}
                                >
                                    {item.itemValue}
                                </Tooltip>
                            </span>
                        </div>
                    )
                );
                return <div>{renderArr}</div>;
            }
        },
        {
            title: '来源',
            dataIndex: 'taskResourceName',
            width: '8%'
        },
        {
            title: '类型',
            dataIndex: 'taskTypeName',
            width: '8%'
        },
        {
            title: '状态',
            dataIndex: 'pendingState',
            width: '6%',
            render: text => (
                <div>
                    {text === 0 && <span>待处理</span>}
                    {text === -1 && <span className={styles.beOverdue}>已逾期</span>}
                </div>
            )
        },
        {
            title: '推送时间',
            dataIndex: 'sendTime',
            width: '10%',
            sortOrder: getOrderState('sendTime'),
            sorter: () => {},
            render: text => (text ? formatDate(text) : '--')
        },
        {
            title: '截止时间',
            dataIndex: 'overdueTime',
            width: '10%',
            sortOrder: getOrderState('overdueTime'),
            sorter: () => {},
            render: (text, record) => (
                <span className={record.pendingState === -1 ? `${styles.beOverdue}` : ''}>
                    {text ? formatDate(text) : '--'}
                </span>
            )
        },
        {
            title: '操作',
            dataIndex: 'action',
            width: '5%',
            render: (text, record) => (
                <>
                    {record.taskType === 'approval' && (
                        <Tooltip title="去审批">
                            <Icon.Button
                                icon="iconApproval_O"
                                dark
                                onClick={() => handleLink(record.targetUrl)}
                                className={styles.actionIcon}
                            />
                        </Tooltip>
                    )}
                    {record.taskType === 'operation' && (
                        <Tooltip title="去处理">
                            <Icon.Button
                                icon="iconlistfunction_readyinterview_icon_default"
                                dark
                                onClick={() => handleLink(record.targetUrl)}
                                className={styles.actionIcon}
                            />
                        </Tooltip>
                    )}
                </>
            )
        }
    ];

    const handleReplacePage = param => {
        setLoading(true);
        history.push({ query: { ...query, ...param } });
    };

    // 分页切换
    const handlePaginationChange = pagination => {
        handleReplacePage({
            pageNo: pagination?.current,
            pageSize: pagination?.pageSize
        });
    };

    // 任务类型(''：全部、approval：审批流程、operation：操作流程、work：工作任务)
    const handleTabsSelect = e => {
        const param = { taskType: e.target.value, pageNo: 1 };
        setTaskType(e.target.value);
        handleReplacePage(param);
    };

    // 清空
    const handleReset = () => {
        setFieldsValue({
            pushRangePicker: undefined,
            taskResource: undefined,
            taskTitle: undefined,
            pendingState: undefined
        });

        const param = {
            pushStartDate: '',
            pushEndDate: '',
            pendingState: '',
            taskTitle: '',
            pageNo: 1,
            pushRangePicker: undefined
        };
        handleReplacePage(param);
    };

    // 视图切换
    const handleViewTabsSelect = e => {
        const param = { viewType: e.target.value };
        handleReplacePage(param);
    };

    // 高级切换
    const toggle = () => {
        setExpand(!expand);
    };

    // 搜索
    const handleSearch = () => {
        validateFields((err, values) => {
            if (!err) {
                const { pushRangePicker: pushRangePickerTime } = values;
                let pushStartDate;
                let pushEndDate;
                // 判断是否有选择时间
                if (pushRangePickerTime?.length > 0) {
                    pushStartDate = moment(pushRangePickerTime[0]).format('YYYY-MM-DD');
                    pushEndDate = moment(pushRangePickerTime[1]).format('YYYY-MM-DD');
                } else {
                    pushStartDate = '';
                    pushEndDate = '';
                }

                const param = {
                    taskType,
                    pushStartDate,
                    pushEndDate,
                    ...values,
                    pageNo: 1
                };
                handleReplacePage(param);
            }
        });
    };

    const handleChange = (pagination, filters, sorter) => {
        const { field, order } = sorter;
        const orderByField = order ? `${field}|${order}` : undefined;
        const param = { orderByField };

        handleReplacePage(param);
    };

    // 需要query作为刷新条件请勿删除;
    const { subContent } = useSubscribeMsg({
        subType: [Msg.todo]
    });

    useEffect(() => {
        run();
    }, [query, run]);

    // 根据URl获取列表数据, 需要query作为刷新条件请勿删除
    useEffect(() => {
        if (subContent?.type === 'todo') {
            run();
        }
    }, [subContent, run]);

    return (
        <PageHeaderWrapper>
            <div className={styles.todoWrapper}>
                <Spin spinning={loading && unFinishCount === undefined && finishCount === undefined}>
                    <div className={styles.todoTypeWrapper}>
                        <TodoSort active="unprocessed" unFinishCount={unFinishCount} finishCount={finishCount} />
                    </div>
                </Spin>
                <div className={styles.todoListWrapper}>
                    <Card
                        title="待处理工作"
                        bordered={false}
                        extra={
                            <div className={styles.cardExtra}>
                                <Radio.Group defaultValue={tabType} onChange={handleTabsSelect}>
                                    <Radio.Button value="">全部</Radio.Button>
                                    <Radio.Button value="approval">审批流程</Radio.Button>
                                    <Radio.Button value="operation">操作流程</Radio.Button>
                                </Radio.Group>
                                <Radio.Group
                                    defaultValue={viewType}
                                    onChange={handleViewTabsSelect}
                                    style={{ marginLeft: 16 }}
                                >
                                    <Radio.Button value="list">
                                        <Icon type="iconzhailiebiaoshitu1" style={{ fontSize: 20 }} />
                                    </Radio.Button>
                                    <Radio.Button value="card">
                                        <Icon type="iconkuanliebiaoshitu1" style={{ fontSize: 20 }} />
                                    </Radio.Button>
                                </Radio.Group>
                            </div>
                        }
                    >
                        <Form {...formItemLayout} layout="inline">
                            <Row gutter={24} className={styles.searchCtr}>
                                <Col span={8}>
                                    <Item label="搜索事项">
                                        {getFieldDecorator('taskTitle', {
                                            initialValue: taskTitle
                                        })(<Input placeholder="请输入关键字" />)}
                                    </Item>
                                </Col>
                                {expand ? (
                                    <>
                                        <Col span={8}>
                                            <Item label="来源">
                                                {getFieldDecorator('taskResource', {
                                                    initialValue: taskResource
                                                })(
                                                    <Select
                                                        placeholder="请选择"
                                                        allowClear
                                                        getPopupContainer={triggerNode => triggerNode.parentElement}
                                                    >
                                                        {messageResourceList?.map(option => (
                                                            <Option value={option?.value} key={option?.value}>
                                                                {option?.text}
                                                            </Option>
                                                        ))}
                                                    </Select>
                                                )}
                                            </Item>
                                        </Col>
                                        <Col span={8}>
                                            <Item label="状态">
                                                {getFieldDecorator('pendingState', {
                                                    initialValue: pendingState ? Number(pendingState) : pendingState
                                                })(
                                                    <Select placeholder="请选择">
                                                        <Option value={0}>待处理</Option>
                                                        <Option value={-1}>已逾期</Option>
                                                    </Select>
                                                )}
                                            </Item>
                                        </Col>
                                        <Col span={8}>
                                            <Item label="推送时间">
                                                {getFieldDecorator('pushRangePicker', {
                                                    initialValue:
                                                        pushRangePicker?.length > 0
                                                            ? [
                                                                  moment(
                                                                      moment(pushRangePicker?.[0]).format('YYYY-MM-DD')
                                                                  ),
                                                                  moment(
                                                                      moment(pushRangePicker?.[1]).format('YYYY-MM-DD')
                                                                  )
                                                              ]
                                                            : undefined
                                                })(
                                                    <RangePicker
                                                        style={{ width: '100%' }}
                                                        format="YYYY-MM-DD"
                                                        getCalendarContainer={trigger => trigger.parentNode}
                                                    />
                                                )}
                                            </Item>
                                        </Col>
                                    </>
                                ) : null}
                                <div className={expand ? styles.up : styles.down}>
                                    <Col>
                                        <Button type="primary" onClick={handleSearch}>
                                            搜索
                                        </Button>
                                        <Button style={{ marginLeft: 12 }} onClick={handleReset}>
                                            清空
                                        </Button>
                                        <a style={{ marginLeft: 16, fontSize: 14 }} onClick={toggle}>
                                            高级搜索 <Icon type={expand ? 'caret-up' : 'caret-down'} />
                                        </a>
                                    </Col>
                                </div>
                            </Row>
                        </Form>
                        {viewType === 'list' ? (
                            <Spin spinning={loading}>
                                <Table
                                    className={styles.listTable}
                                    rowKey={row => row.id}
                                    columns={columns}
                                    dataSource={todoList}
                                    pagination={false}
                                    onChange={handleChange}
                                    onRow={record => ({
                                        onClick: () => {
                                            handleLink(record?.targetUrl);
                                        }
                                    })}
                                />
                            </Spin>
                        ) : (
                            <Spin spinning={loading}>
                                {todoList?.length < 1 ? (
                                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                                ) : (
                                    <>
                                        {todoList?.map(item => (
                                            <TodoCard todo={item} key={`${item.id}_my_todo`} />
                                        ))}
                                    </>
                                )}
                            </Spin>
                        )}

                        <Pagination
                            current={query?.pageNo}
                            pageSize={query?.pageSize}
                            total={total}
                            onChange={handlePaginationChange}
                        />
                    </Card>
                </div>
            </div>
        </PageHeaderWrapper>
    );
};

export default withRouter(createForm()(Todo));
